Setup & Configuration
Set User Identity
bash
1git config --global user.name "Your Name"2git config --global user.email "[email protected]"View Configuration
bash
1git config --list # show all settings2git config --list --show-origin # show settings with file locations3git config user.name # show single valueSet Default Branch Name
bash
1git config --global init.defaultBranch mainSet Default Editor
bash
1git config --global core.editor "code --wait" # VS Code2git config --global core.editor "vim" # Vim3git config --global core.editor "nano" # NanoCredential & Auth Helpers
bash
1git config --global credential.helper cache # cache for 15 min2git config --global credential.helper 'cache --timeout=3600' # cache 1 hour3git config --global credential.helper store # save to disk (plain text)Line Ending Configuration
bash
1git config --global core.autocrlf input # macOS/Linux (LF)2git config --global core.autocrlf true # Windows (CRLF → LF on commit)Creating & Cloning Repositories
Initialize a New Repo
bash
1git init # init in current directory2git init my-project # create new directory & init3git init --bare my-repo.git # bare repo (for servers)Clone an Existing Repo
bash
1git clone https://github.com/user/repo.git2git clone https://github.com/user/repo.git my-folder # custom directory3git clone [email protected]:user/repo.git # SSHClone a Specific Branch
bash
1git clone -b branch-name https://github.com/user/repo.git2git clone -b v2.0 --single-branch https://github.com/user/repo.git # single branch onlyShallow Clone
bash
1git clone --depth 1 https://github.com/user/repo.git # latest commit only2git clone --depth 10 https://github.com/user/repo.git # last 10 commits3git clone --shallow-since="2024-01-01" https://github.com/user/repo.gitStaging & Snapshotting
Check Status
bash
1git status2git status -s # short format3git status -sb # short + branch infoStage Files
bash
1git add file.txt # stage a single file2git add src/ # stage entire directory3git add . # stage all changes in current dir4git add -A # stage all changes in entire repo5git add *.js # stage by pattern6git add -p # interactive staging (hunk by hunk)Unstage Files
bash
1git restore --staged file.txt # modern syntax2git restore --staged . # unstage everything3git reset HEAD file.txt # older syntaxCommit Changes
bash
1git commit -m "commit message"2git commit -am "message" # stage tracked files + commit3git commit --amend # edit last commit message4git commit --amend --no-edit # add staged changes to last commit silently5git commit --allow-empty -m "msg" # empty commit (useful for CI triggers)6git commit -m "title" -m "body" # multi-line: title + descriptionDiscard Local Changes
bash
1git restore file.txt # discard working directory changes2git restore . # discard all changes3git restore --source=HEAD --staged --worktree file.txt # restore both index & working tree4git checkout -- file.txt # older syntaxMove & Remove Files
bash
1git mv old-name.txt new-name.txt # rename/move tracked file2git rm file.txt # remove from working tree & index3git rm --cached file.txt # untrack but keep on disk4git rm -r --cached folder/ # untrack entire folderBranching
List Branches
bash
1git branch # local branches2git branch -r # remote branches3git branch -a # all branches4git branch -v # branches with last commit5git branch -vv # branches with upstream tracking info6git branch --merged # branches merged into current7git branch --no-merged # branches not yet mergedCreate a Branch
bash
1git branch new-branch # create only2git checkout -b new-branch # create and switch3git switch -c new-branch # create and switch (modern)4git checkout -b feature origin/feature # track remote branch5git switch -c feature --track origin/featureSwitch Branches
bash
1git checkout branch-name2git switch branch-name # modern syntax3git switch - # switch to previous branchRename a Branch
bash
1git branch -m old-name new-name # rename specific branch2git branch -m new-name # rename current branch3# After renaming, update remote:4git push origin --delete old-name5git push -u origin new-nameDelete a Branch
bash
1git branch -d branch-name # safe delete (merged only)2git branch -D branch-name # force delete3git push origin --delete branch-name # delete remote branchMerging & Rebasing
Merge a Branch into Current
bash
1git merge branch-name2git merge --no-ff branch-name # always create merge commit3git merge --squash branch-name # squash all commits into one (then git commit)Abort a Merge
bash
1git merge --abortResolve Conflicts
bash
1# After fixing conflicts manually:2git add resolved-file.txt3git commit # finalize merge4# Or pick a side:5git checkout --ours file.txt # keep current branch version6git checkout --theirs file.txt # keep incoming branch versionRebase
bash
1git rebase main # rebase onto main2git rebase -i HEAD~3 # interactive rebase last 3 commits3git rebase -i --autosquash HEAD~5 # auto-reorder fixup/squash commits4git rebase --onto main feature bugfix # rebase bugfix onto main (skip feature)5git rebase --abort # cancel rebase6git rebase --continue # after resolving conflicts7git rebase --skip # skip current conflicting commitInteractive Rebase Actions
bash
1# Inside the interactive rebase editor:2# pick = use commit as-is3# reword = edit commit message4# edit = pause to amend the commit5# squash = merge into previous commit (keep message)6# fixup = merge into previous commit (discard message)7# drop = remove commit entirelyRemote Repositories
View Remotes
bash
1git remote -v # list remotes with URLs2git remote show origin # detailed info about a remoteAdd a Remote
bash
1git remote add origin https://github.com/user/repo.git2git remote add upstream https://github.com/original/repo.gitChange Remote URL
bash
1git remote set-url origin https://github.com/user/new-repo.git2git remote set-url origin [email protected]:user/repo.git # switch to SSHRename & Remove Remotes
bash
1git remote rename origin upstream2git remote remove originFetch, Pull & Push
Fetch (Download Without Merging)
bash
1git fetch # fetch from default remote2git fetch origin # fetch from specific remote3git fetch --all # fetch from all remotes4git fetch --prune # remove stale remote-tracking branches5git fetch origin --tags # fetch all tags from remote6git fetch origin branch-name # fetch a specific branchPull (Fetch + Merge)
bash
1git pull # pull current branch2git pull origin main # pull specific branch3git pull --rebase # fetch + rebase instead of merge4git pull --rebase=interactive # interactive rebase on pull5git pull --autostash # auto-stash before pull, apply after6git pull --ff-only # only fast-forward (fail if diverged)Push
bash
1git push # push current branch2git push origin main # push specific branch3git push -u origin main # set upstream tracking and push4git push --all # push all branches5git push --tags # push all tags6git push origin v1.0.0 # push a specific tag7git push --force # force push ⚠️ destructive — rewrites remote8git push --force-with-lease # safer force push (fails if remote has new commits)9git push origin --delete branch # delete remote branchStashing
Save Changes to Stash
bash
1git stash # stash tracked changes2git stash -u # include untracked files3git stash -a # include untracked + ignored files4git stash push -m "description" # with a message (modern)5git stash push src/file.txt # stash specific filesList & Apply Stashes
bash
1git stash list # list all stashes2git stash show # show latest stash summary3git stash show -p # show latest stash diff4git stash apply # apply latest stash (keep in stash)5git stash pop # apply latest stash and remove it6git stash apply stash@{2} # apply specific stashDrop & Branch from Stash
bash
1git stash drop # remove latest stash2git stash drop stash@{2} # remove specific stash3git stash clear # remove all stashes4git stash branch new-branch # create branch from stash and applyViewing History & Diffs
View Commit Log
bash
1git log # full log2git log --oneline # compact format3git log --oneline --graph --all # graph with all branches4git log --oneline --decorate --graph # with branch/tag names5git log --author="Name" # filter by author6git log --grep="fix" # search commit messages7git log -n 5 # last 5 commits8git log --since="2024-01-01" # commits since date9git log --until="2024-06-01" # commits until date10git log --after="1 week ago" # relative dates11git log -- file.txt # history of specific file12git log --follow file.txt # follow renames13git log --stat # include file change stats14git log --pretty=format:"%h %an %s" # custom formatPretty Log Formats
bash
1# Useful custom formats:2git log --pretty=format:"%C(red)%h%Creset %s %C(blue)(%an)%Creset"3git log --pretty=format:"%h %ad %s" --date=shortView Differences
bash
1git diff # unstaged changes2git diff --staged # staged changes (same as --cached)3git diff HEAD # all changes since last commit4git diff main..feature # diff between branches5git diff main...feature # changes in feature since branching from main6git diff HEAD~2 # diff from 2 commits ago7git diff --stat # summary of changes8git diff --name-only # only file names9git diff --name-status # file names with status (M/A/D)10git diff --word-diff # inline word-level diffShow a Specific Commit
bash
1git show abc1234 # full commit details2git show HEAD # latest commit3git show HEAD~2 # 2 commits ago4git show HEAD:src/file.txt # file content at commit5git show --stat abc1234 # commit stats onlyBlame (Line-by-Line Authorship)
bash
1git blame file.txt2git blame -L 10,20 file.txt # specific line range3git blame -w file.txt # ignore whitespace changes4git blame -C file.txt # detect moved/copied linesShortlog (Summary by Author)
bash
1git shortlog -sn # count commits per author2git shortlog -sn --no-merges # exclude merge commitsUndoing & Resetting
Reset Commits
bash
1git reset --soft HEAD~1 # undo commit, keep changes staged2git reset --mixed HEAD~1 # undo commit, unstage changes (default)3git reset --hard HEAD~1 # undo commit, discard all changes ⚠️4git reset --hard origin/main # reset to match remote exactly ⚠️Revert a Commit (Safe Undo)
bash
1git revert abc1234 # create new commit that undoes changes2git revert HEAD # revert last commit3git revert HEAD~3..HEAD # revert last 3 commits4git revert --no-commit abc1234 # stage revert without committingCherry-Pick (Apply Specific Commits)
bash
1git cherry-pick abc1234 # apply a single commit2git cherry-pick abc1234 def5678 # apply multiple commits3git cherry-pick abc1234..def5678 # apply range of commits4git cherry-pick --no-commit abc1234 # stage without committing5git cherry-pick --abort # cancel in-progress cherry-pickRecover Lost Commits
bash
1git reflog # view history of HEAD movements2git reflog show feature-branch # reflog for specific branch3git checkout abc1234 # go to a specific commit (detached HEAD)4git branch recovery abc1234 # create branch from lost commitTags
List Tags
bash
1git tag # list all tags2git tag -l "v1.*" # filter tags by pattern3git tag -l --sort=-version:refname "v*" # sort by version descendingCreate Tags
bash
1git tag v1.0.0 # lightweight tag2git tag -a v1.0.0 -m "Release 1.0.0" # annotated tag (recommended)3git tag -a v1.0.0 abc1234 # tag a past commitPush Tags
bash
1git push origin v1.0.0 # push single tag2git push origin --tags # push all tags3git push --follow-tags # push commits + annotated tagsDelete Tags
bash
1git tag -d v1.0.0 # delete local tag2git push origin --delete v1.0.0 # delete remote tag3git push origin :refs/tags/v1.0.0 # alternative delete syntaxShow Tag Info
bash
1git show v1.0.0 # show tag details and commit2git describe # describe HEAD relative to nearest tag3git describe --tags --abbrev=0 # nearest tag name onlyAdvanced: Bisect, Worktree & Submodules
Bisect (Binary Search for Bugs)
bash
1git bisect start # begin bisect session2git bisect bad # mark current commit as bad3git bisect good abc1234 # mark a known good commit4# Git checks out a midpoint — test it, then:5git bisect good # if this commit works6git bisect bad # if this commit is broken7# Repeat until Git finds the first bad commit8git bisect reset # end bisect, return to original branch9git bisect log # view bisect history10git bisect replay log.txt # replay a saved bisect sessionAutomated Bisect
bash
1git bisect start HEAD abc12342git bisect run ./test-script.sh # auto-test each step (exit 0 = good)Worktrees (Multiple Working Directories)
bash
1git worktree list # list all worktrees2git worktree add ../hotfix-tree hotfix-branch # create linked worktree3git worktree add -b new-branch ../new-tree # create worktree + new branch4git worktree remove ../hotfix-tree # remove a worktree5git worktree move ../old-path ../new-path # move a worktreeSubmodules
bash
1git submodule add https://github.com/user/lib.git libs/lib # add submodule2git submodule init # initialize submodule config3git submodule update # fetch & checkout submodule commits4git submodule update --init # init + update in one step5git submodule update --init --recursive # include nested submodules6git submodule update --remote # update to latest remote commit7git submodule foreach git pull origin main # pull in all submodules8git submodule status # show submodule commit SHAs9git submodule deinit libs/lib # unregister a submodule10git rm libs/lib # remove submodule from projectSparse Checkout (Partial Repo)
bash
1git sparse-checkout init --cone # enable cone mode2git sparse-checkout set src/ docs/ # only checkout these dirs3git sparse-checkout add tests/ # add more dirs4git sparse-checkout list # show checked-out dirs5git sparse-checkout disable # disable, restore full repoGitHub CLI (gh)
Authentication
bash
1gh auth login # interactive login2gh auth login --web # browser-based login3gh auth login --with-token < token.txt # token from file4gh auth login --hostname enterprise.internal # GitHub Enterprise5gh auth status # check auth status6gh auth logout # log out7gh auth refresh --scopes write:packages # add extra scopesRepository Management
bash
1gh repo create my-repo --public # create public repo2gh repo create my-org/project --private # create in org3gh repo create --source=. --remote=origin --push # from local dir4gh repo clone user/repo # clone a repo5gh repo fork user/repo # fork a repo6gh repo fork user/repo --clone # fork and clone locally7gh repo fork --org my-org # fork into organization8gh repo view # view repo info9gh repo view --web # open in browser10gh repo set-default owner/repo # set default repo for CLI11gh repo list user --limit 50 # browse reposPull Requests
bash
1gh pr create --title "Title" --body "Body" # create PR2gh pr create --fill # auto-fill from commits3gh pr create --draft # create as draft4gh pr create --web # open creation page in browser5gh pr create --base main --head feature # specify branches6gh pr list # list open PRs7gh pr list --state all # list all PRs8gh pr view 42 # view PR details9gh pr view 42 --web # open PR in browser10gh pr checkout 42 # checkout PR locally11gh pr diff 42 # view PR diff12gh pr merge 42 # merge PR13gh pr merge 42 --squash # squash merge14gh pr merge 42 --rebase # rebase merge15gh pr merge 42 --auto # auto-merge when checks pass16gh pr close 42 # close without merging17gh pr reopen 42 # reopen a closed PR18gh pr review 42 --approve # approve PR19gh pr review 42 -r -b "needs changes" # request changes20gh pr revert 42 # revert a merged PRSearch PRs
bash
1gh search prs "fix bug" --repo=user/repo2gh search prs --review-requested=@me --state=open3gh search prs --author=@me --merged4gh search prs --assignee=@me --draftIssues
bash
1gh issue create --title "Bug" --body "Details"2gh issue create --label "bug,urgent" # with labels3gh issue create --assignee @me # assign to self4gh issue list # list open issues5gh issue list --state all --limit 1006gh issue list --label "bug" # filter by label7gh issue view 42 # view issue details8gh issue close 42 # close issue9gh issue reopen 42 # reopen issue10gh issue edit 42 --add-label "priority" # edit labels11gh issue comment 42 --body "Working on this"Releases
bash
1gh release create v1.0.0 # create release2gh release create v1.0.0 --generate-notes # auto-generate notes3gh release create v1.0.0 --draft # create draft release4gh release create v1.0.0 ./build.zip # upload asset5gh release list # list releases6gh release view v1.0.0 # view release7gh release download v1.0.0 # download assets8gh release delete v1.0.0 # delete releaseGists
bash
1gh gist create file.txt # create gist from file2gh gist create file.txt --public # public gist3gh gist create -d "description" file.txt # with description4gh gist list # list your gists5gh gist view <id> # view gist6gh gist clone <id> # clone gist locally7gh gist edit <id> # edit a gist8gh gist delete <id> # delete a gistWorkflow Runs (GitHub Actions)
bash
1gh workflow list # list workflows2gh workflow view deploy.yml # view workflow details3gh workflow run deploy.yml # trigger workflow manually4gh workflow run deploy.yml -f env=production # with input parameters5gh run list # list recent runs6gh run view 12345 # view run summary7gh run view 12345 --log # full run log8gh run view 12345 --log-failed # only failed step logs9gh run watch 12345 # live-watch a run10gh run rerun 12345 # rerun a workflow11gh run cancel 12345 # cancel a run12gh run download 12345 # download run artifactsSecrets & Variables
bash
1gh secret set MY_SECRET # set repo secret (prompt)2gh secret set MY_SECRET < secret.txt # set from file3gh secret set MY_SECRET --env production # environment secret4gh secret set MYSECRET --user # user-level (Codespaces)5gh secret list # list repo secrets6gh secret delete MY_SECRET # delete a secret7gh variable set MY_VAR --body "value" # set a variable8gh variable list # list variablesSSH & GPG Keys
bash
1gh ssh-key list # list SSH keys2gh ssh-key add ~/.ssh/id_ed25519.pub # add SSH key3gh gpg-key list # list GPG keys4gh gpg-key add key.pub # add GPG keyGitHub API (Direct Access)
bash
1gh api repos/user/repo # GET request2gh api repos/user/repo/issues -f title="Bug" # POST with fields3gh api --method DELETE repos/user/repo/issues/14gh api graphql -f query='{ viewer { login } }' # GraphQL query5gh api repos/{owner}/{repo}/releases --jq '.[0].tag_name' # with jq filterCleanup & Maintenance
Remove Untracked Files
bash
1git clean -n # dry run — show what would be removed2git clean -f # remove untracked files3git clean -fd # remove untracked files and directories4git clean -fX # remove only ignored files5git clean -fdx # remove untracked + ignored files & dirs ⚠️Garbage Collection
bash
1git gc # standard cleanup2git gc --aggressive # deeper optimization3git gc --prune=now # prune all unreachable objects immediatelyPrune & Verify
bash
1git remote prune origin # remove stale remote-tracking branches2git fetch --prune # prune during fetch3git prune # remove unreachable objects4git fsck # verify repository integrityCount Objects & Repo Size
bash
1git count-objects -vH # human-readable object count & size2git rev-list --count HEAD # total commit countUseful Aliases
bash
1git config --global alias.st "status -sb"2git config --global alias.co checkout3git config --global alias.br branch4git config --global alias.ci commit5git config --global alias.unstage "restore --staged"6git config --global alias.last "log -1 HEAD --stat"7git config --global alias.lg "log --oneline --graph --all --decorate"8git config --global alias.amend "commit --amend --no-edit"9git config --global alias.undo "reset --soft HEAD~1"10git config --global alias.contributors "shortlog -sn --no-merges"11git config --global alias.aliases "config --get-regexp alias".gitignore Patterns
bash
1# Common patterns2*.log # ignore all .log files3node_modules/ # ignore directory4dist/ # ignore build output5.env # ignore env files6.env.* # ignore all env variants7!.env.example # exception — track this one8**/*.tmp # ignore .tmp in any nested directory9build/ # ignore build folder10*.DS_Store # macOS system files11Thumbs.db # Windows system filesGlobal .gitignore
bash
1git config --global core.excludesfile ~/.gitignore_global